﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace AOYOU.Framework.Utility
{
    [System.Serializable]
    public class SerializationHelper
    {


        #region ========== XmlSerializer ==========
        /// <summary>
        /// 序列化，使用标准的XmlSerializer，优先考虑使用。
        /// 不能序列化IDictionary接口.
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="filename">文件路径</param>
        public static string Save(object obj, string filename)
        {
            FileStream fs = null;
            MemoryStream ms = null;

            // serialize it...
            try
            {
                //防止序列化出错更新到配置文件 所以先完成序列化 在保存
                XmlSerializer serializer = new XmlSerializer(obj.GetType());
                ms = new MemoryStream(13 * 1024); //初始缓冲区大小13k
                serializer.Serialize(ms, obj);

                string tmpContent = System.Text.Encoding.UTF8.GetString(ms.GetBuffer());

                fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                ms.WriteTo(fs);

                ms.Flush();
                fs.Flush();

                return tmpContent;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (ms != null)
                {
                    ms.Close();
                    ms.Dispose();
                }
            }

        }

        /// <summary>
        /// 反序列化，使用标准的XmlSerializer，优先考虑使用。
        /// 不能序列化IDictionary接口.
        /// </summary>
        /// <param name="type">对象类型</param>
        /// <param name="filename">文件路径</param>
        /// <returns>type类型的对象实例</returns>
        public static object Load(Type type, string filename)
        {
            FileStream fs = null;
            try
            {
                // open the stream...
                fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(type);
                return serializer.Deserialize(fs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }

        /// <summary>
        /// 反序列化类
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="filename">文件名</param>
        /// <returns></returns>
        public static T Load<T>(string filename) where T : class
        {
            FileStream fs = null;
            try
            {
                // open the stream...
                fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                return serializer.Deserialize(fs) as T;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
        }

        #endregion


        #region ========== BinaryBytes ==========
        /// <summary>
        /// 将对象使用二进制格式序列化成byte数组
        /// </summary>
        /// <param name="obj">待保存的对象</param>
        /// <returns>byte数组</returns>
        public static byte[] SaveToBinaryBytes(object obj)
        {
            //将对象序列化到MemoryStream中
            MemoryStream ms = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            //从MemoryStream中获取获取byte数组
            return ms.ToArray();
        }

        /// <summary>
        /// 将使用二进制格式保存的byte数组反序列化成对象
        /// </summary>
        /// <param name="bytes">byte数组</param>
        /// <returns>对象</returns>
        public static object LoadFromBinaryBytes(byte[] bytes)
        {
            object result = null;
            BinaryFormatter formatter = new BinaryFormatter();
            if (bytes != null)
            {
                MemoryStream ms = new MemoryStream(bytes);
                result = formatter.Deserialize(ms);
            }
            return result;
        }
        #endregion


        #region ========= other ==========
        /// <summary>
        /// 使用BinaryFormatter将对象系列化到MemoryStream中。
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>保存对象的MemoryStream</returns>
        public static MemoryStream SaveToMemoryStream(object obj)
        {
            MemoryStream ms = new MemoryStream();
            BufferedStream stream = new BufferedStream(ms);
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            return ms;
        }


        /// <summary>
        /// Creates xml string from given dto.
        /// </summary>
        /// <param name="dto">DTO</param>
        /// <returns>XML</returns>
        public static string SerializeDTO(Object dto)
        {
            try
            {
                XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
                StringWriter sWriter = new StringWriter();
                // Serialize the dto to xml.
                xmlSer.Serialize(sWriter, dto);
                // Return the string of xml.
                return sWriter.ToString();
            }
            catch (Exception ex)
            {
                // Propogate the exception.
                //throw ex;
                return ex.Message;
            }
        }

        #endregion

        /// <summary>
        /// 序列化 对象到字符串；
        /// BinaryFormatter
        /// </summary>
        /// <param name="obj">泛型对象</param>
        /// <returns>序列化后的字符串</returns>
        public static string SerializeViaBinaryFormatter<T>(T obj)
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                MemoryStream stream = new MemoryStream();
                formatter.Serialize(stream, obj);
                stream.Position = 0;
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                stream.Flush();
                stream.Close();
                return Convert.ToBase64String(buffer);
            }
            catch (Exception ex)
            {
                throw new Exception("序列化失败,原因:" + ex.Message);
            }
        }

        /// <summary>
        /// 反序列化 字符串到对象；
        /// BinaryFormatter
        /// </summary>
        /// <param name="obj">泛型对象</param>
        /// <param name="str">要转换为对象的字符串</param>
        /// <returns>反序列化出来的对象</returns>
        public static T DesrializeViaBinaryFormatter<T>(T obj, string str)
        {
            try
            {
                if (str.Length == 0)
                    return default(T);
                obj = default(T);
                IFormatter formatter = new BinaryFormatter();
                byte[] buffer = Convert.FromBase64String(str);
                MemoryStream stream = new MemoryStream(buffer);
                obj = (T)formatter.Deserialize(stream);
                stream.Flush();
                stream.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("反序列化失败,原因:" + ex.Message);
            }
            return obj;
        }

        /// <summary>
        /// 序列化 对象到字符串；
        /// XmlSerializer
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string XmlSerialize(object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            StringWriter sr = new StringWriter();
            try
            {
                XmlSerializer xs = new XmlSerializer(obj.GetType());
                xs.Serialize(sr, obj);
            }
            catch (Exception ex)
            {
                throw new Exception("XmlSerialize序列化失败,原因:" + ex.Message);
            }
            return sr.ToString();
        }

        /// <summary>
        /// 序列化 对象到字符串；
        /// XmlSerializer
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static object XmlDeserialize(string xml, Type t)
        {
            if (string.IsNullOrEmpty(xml))
            {
                return null;
            }
            StringReader sr = new StringReader(xml);
            try
            {
                XmlSerializer xs = new XmlSerializer(t);
                object val = xs.Deserialize(sr);
                return val;
            }
            catch (Exception ex)
            {
                throw new Exception("XmlSerialize反序列化失败,原因:" + ex.Message);
                return null;
            }
        }
    }
}
